/*******************************************************************************
 *            SHOPPING CART COLLECTIONS CLASS EXTENDS COLLECTION CLASS
 ******************************************************************************/
function CartCollection() {};
//inherit from Collection class
CartCollection.prototype = new Collection();
//reset the constructor after inheritance
CartCollection.prototype.constructor = CartCollection;

//Create Data for SaleItem Model
CartCollection.prototype.createProformaItemModelData = function() {
    var self = this;
    var data = [];
    self.iterate(function(key,obj){
        var id = key
        var quantity = obj.quantity;
        var discount = obj.discount;

        data.push({
            item_id:id,
            quantity:quantity,
            discount:discount
        });
    });

    return data;
}

/*******************************************************************************
 *            END OF SHOPPING CART COLLECTIONS CLASS
 ******************************************************************************/


/*
 * @name administration.js
 * @author : Amissah Gideon<kuulmek@yahoo.com>
 */
var NewProforma = {
    /* Function init
     * @param void
     * @return void
     * @access public
     * */

    _cart: new CartCollection(),
     current_customer:null,
    sales_type:'out_right_purchase',

     init:function () {
        var self = this;

         self._cart.registerCallback('add', function(key, obj) {
             self.refreshCartUI();
         });

         self._cart.registerCallback('remove', function(key) {
             self.refreshCartUI();
         });

        Calendar.setup({
            inputField : "date_of_commence",
            trigger    : "date_of_commence_btn",
            onSelect   : function() { this.hide() },
            dateFormat: "%B %d, %Y",
            showTime: false,
            animation: true
        });

         //Config sales type radio
         $('#sales-type-radio-1,#sales-type-radio-2').click(function () {
             var value = $(this).val();
             self.sales_type = value;
         });

        $('#all_customers').change(function () {
            var id = $(this).val();
            var name =  $(this).find("option:selected").text();
            self.setCurrentCustomer(id,name);
        });

        //if Customer does not exit then add new customer
        $('#add-new-customer').click(function () {
            $.colorbox({
                inline:true,
                scrolling:false,
                overlayClose:false,
                escKey:false,
                title:'Customer Information',
                href:'#customer-form-window'
            });
            $('#customer-form-window #customer-form #country_id').val('82');
            $('#customer-form-window #customer-form #country_id').change();
        });

        $('#save-customer-btn').click(function () {
            self.saveNewCustomer();
        });

        $('#cancel-customer-btn').click(function () {
            document.getElementById('customer-form').reset();
            $.validationEngine.closePrompt('.formError', true);
            $.colorbox.close();
        });

        $("#customer-form").validationEngine();
         jLib.afterClosePopUpForm('customer-form',function(){
             document.getElementById('customer-form').reset();
         });

        //Processing adding items
         $('#all_items').change(function () {
             var id = $(this).val();
             if(id == 0){
                 return;
             }
             if(self.current_customer == null){
                 jLib.serverError('Please select or create a new customer prior to this action.');
                 return;
             }

             var name =  $(this).find("option:selected").text();
             $('#item-form-window #item-form #item-label-name').html(name);
             $('#item-form-window #item-form #item_id').val(id);
             $('#item-form-window #item-form #item_name').val(name);
             $.colorbox({
                 inline:true,
                 scrolling:false,
                 overlayClose:false,
                 escKey:false,
                 title:'Item Information',
                 href:'#item-form-window'
             });
         });
         $("#item-form").validationEngine();
         jLib.afterClosePopUpForm('item-form',function(){
             document.getElementById('item-form').reset();
         });
         $('#save-item-btn').click(function () {
             self.addItem();
         });
         $('#cancel-item-btn').click(function () {
             document.getElementById('item-form').reset();
             $.validationEngine.closePrompt('.formError', true);
             $.colorbox.close();
         });

         //Bind the table menus
         $("#invoice_table tbody tr td button").live('click',function(){
             var type = $(this).attr('data-type');
             var id = $(this).attr('data-id');
             if(type == 'edit'){
                var data = self._cart.get(id);
                 $('#item-form-window #item-form #item-label-name').html(data.name);
                 $('#item-form-window #item-form #item_id').val(data.id);
                 $('#item-form-window #item-form #item_name').val(data.name);
                 $('#item-form-window #item-form #quantity').val(data.quantity);
                 $('#item-form-window #item-form #discount').val(data.discount);
                 $.colorbox({
                     inline:true,
                     scrolling:false,
                     overlayClose:false,
                     escKey:false,
                     title:'Item Information',
                     href:'#item-form-window'
                 });
             }
             else{
                 self.removeItem(id);
             }
         });

         //Invoice processing
         $("#generate-invoice-btn").click(function(){
            self.save();
         });
         $("#clear-invoice-btn").click(function(){
             self._cart.clear();
             $('#all_items').val(0);
             $('#all_items').change();
             $('#all_customers').val(0);
             $('#all_customers').change();
             $('#legend-text').html("Invoice");
             self.current_customer = null;
         });

         $("#proforma-form").validationEngine();

    },

    setCurrentCustomer:function(id,name){
        var self = this;
        if(id == 0){
            return;
        }
        if(id == undefined){
            id = $('#all_customers').val();
            name =  $('#all_customers option:selected').text();
        }
        $('#legend-text').html(name+"'s Invoice");
        self.current_customer = id;
    },

    saveNewCustomer:function(){
        var self = this;
        /* Validate the form*/
        var validationStatus =  $('#customer-form').validationEngine({returnIsValid:true});
        /* When the Validation Status is true meaning that the data input are correct then the data can be processed. */
        if(validationStatus){

            jLib.showFormLoading();

            var query = 'model=Customer&row_id='+self.selected_row_id+'&'+ $('#customer-form').serialize();
            /* Send the data to the server and handle the server response */
            var url = $("#add-edit-url").val();


            $.ajax({
                url:url,
                data:query,
                dataType:'json',
                type:'POST',
                success:function (response) {
                    var txt = '';
                    if (typeof response.mesg == 'object') {
                        for (megTxt in response.mesg) {
                            txt += response.mesg[megTxt] + '<br />';
                        }
                    }
                    else {
                        txt = response.mesg
                    }
                    //* When everything went on smoothly on the server redirect the user to the appropriate page.*//*
                    if (response.code === 0) {

                        jLib.message(txt, 'success');
                        var id = response.data.id;
                        var name = response.data.name;
                        var select = document.getElementById('all_customers');
                        var opt = document.createElement('option');
                        opt.value = id;
                        opt.text = name;
                        try{ //Standard
                            select.add(opt,null) ;
                        }
                        catch(error){ //IE Only
                            select.add(opt) ;
                        }
                        //reapply custom select to update the options
                        jLib.refreshCustomElement($("#all_customers"),'select');
                        $('#all_customers').val(id);
                        $('#all_customers').change();

                        document.getElementById('customer-form').reset();
                        $.validationEngine.closePrompt('.formError',true);
                        $.colorbox.close();
                    }
                    //* When there are Errors *//*
                    else if (response.code === 1) {
                        jLib.serverError(txt);
                    }

                    jLib.hideFormLoading();
                },
                error:function (xhr) {
                    console.log(xhr.responseText);
                    jLib.serverError();
                }
            });
        }
    },


    addItem:function(){
        var self = this;

        var id = $("#item-form #item_id").val();
        if(id == 0){
            return false;
        }
        var name = $("#item-form #item_name").val();
        var quantity = $("#item-form #quantity").val();
        var discount = $("#item-form #discount").val();

        self._cart.add(id,{id:id,name:name,quantity:quantity,discount:discount});
        $.colorbox.close();
    },

    removeItem:function(id){
        var self = this;
        if(id == 0){
            return false;
        }
        self._cart.remove(id);
    },

    refreshCartUI:function(){
        var self = this;

        $("#invoice_table tbody").html('');
        self._cart.iterate(function(key, obj){
            var id = key
            var name = obj.name;
            var quantity = obj.quantity
            var discount = obj.discount;

            var btn_str = "<button type='button' class='button compact' data-type='edit' data-id='"+id+"'>";
                btn_str +=  "<span class='button-icon grey-gradient'><span class='icon-pencil'></span></span>";
                btn_str +=      "Edit";
                btn_str += "</button> &nbsp;&nbsp;";
                btn_str += "<button type='button' class='button compact' data-type='remove' data-id='"+id+"'>";
                btn_str +=  "<span class='button-icon red-gradient'><span class='icon-cross-round'></span></span>";
                btn_str +=      "Remove";
                btn_str +="</button>";

            var tr = $("<tr />").attr('data-id',key);
            tr.append($("<td />").html(name))
                .append($("<td />").html(quantity))
                .append($("<td />").html(discount))
                .append($("<td />").html(btn_str));
            $("#invoice_table tbody").append(tr);
        });
    },


    save:function () {
        var self = this;

        var validationStatus =  $('#proforma-form').validationEngine({returnIsValid:true});
        /* When the Validation Status is true meaning that the data input are correct then the data can be processed. */
        if(!validationStatus){
            return;
        }

        if(self.current_customer == null){
            return;
        }
        if(self._cart.getSize() == 0){
            jLib.builPopUpPrompt('.invoice_table','Cart is Empty','error',false);
            return;
        }

        jLib.showFormLoading();

        var data = {
            'Proforma':{
                customer_id:self.current_customer,
                officer_incharge:$('#officer_incharge').val(),
                fon_number:$('#fon_number').val(),
                sales_type:self.sales_type
            },
            'ProformaItem':self._cart.createProformaItemModelData()
        };

        var url = $('#add-edit-url').val();
        var query = 'model=Proforma&data=' + encodeURIComponent(JSON.stringify(data));

        $.ajax({
            url:url,
            data:query,
            dataType:'json',
            type:'POST',
            success:function (response) {
                var txt = '';
                if (typeof response.mesg == 'object') {
                    for (megTxt in response.mesg) {
                        txt += response.mesg[megTxt] + '<br />';
                    }
                }
                else {
                    txt = response.mesg
                }
                //* When everything went on smoothly on the server redirect the user to the appropriate page.*//*
                if (response.code === 0) {
                    /* Alert the user that the server response*/
                    var proforma_id = response.data.id;

                    jLib.message(txt, 'success');

                    //Reset the form
                    $('#clear-invoice-btn').click();
                    var action = $('#print-invoice-url').val();
                    var url = action+'/'+proforma_id;

                    window.open(url,action,"menubar=yes, width=600, height=500,location=no,status=no,scrollbars=yes,resizable=yes");

                }
                //* When there are Errors *//*
                else if (response.code === 1) {
                    jLib.serverError(txt);
                }

                jLib.hideFormLoading();
            },
            error:function (xhr) {
                console.log(xhr.responseText);
                jLib.serverError();
            }
        });

    }

};

/* when the page is loaded */
$(document).ready(function () {
    NewProforma.init();
});